import { WeaRichText, WeaCheckbox, WeaLocaleProvider } from 'ecCom';
import { Button, message } from 'antd';
import { inject, observer } from 'mobx-react';
import isFunction from 'lodash/isFunction';
import isEqual from 'lodash/isEqual';
import { toJS } from 'mobx';

const getLabel = WeaLocaleProvider.getLabel;

@inject('coworkMainStore', 'coworkStoreMap')
@observer
class CoworkRichText extends React.Component {
  constructor(props) {
    super(props);
    this.initValue = {
      richValue: '',
      anonymous: 0,
      relatedaccList4E9: [],
      relatedcusList4E9: [],
      relateddocList4E9: [],
      relatedprjList4E9: [],
      relatedwfList4E9: [],
      relatemutilprjs4E9: [],
    };
    this.state = {
      disableSubmit: false,
      atUserIds: '',
      ...this.initValue,
      richValue: props.richValue,
      anonymous: props.anonymous,
      relatedaccList4E9: props.relatedaccList4E9 || [],
      relatedcusList4E9: props.relatedcusList4E9 || [],
      relateddocList4E9: props.relateddocList4E9 || [],
      relatedprjList4E9: props.relatedprjList4E9 || [],
      relatedwfList4E9: props.relatedwfList4E9 || [],
      relatemutilprjs4E9: props.relatemutilprjs4E9 || [],
    };
  }
  componentWillReceiveProps(nextProps) {
    let newState = {};
    if (nextProps.richValue != this.props.richValue) {
      newState.richValue = nextProps.richValue;
    }
    if (!isEqual(nextProps.relatedaccList4E9, this.props.relatedaccList4E9)) {
      newState.relatedaccList4E9 = nextProps.relatedaccList4E9;
    }
    if (!isEqual(nextProps.relatedcusList4E9, this.props.relatedcusList4E9)) {
      newState.relatedcusList4E9 = nextProps.relatedcusList4E9;
    }
    if (!isEqual(nextProps.relateddocList4E9, this.props.relateddocList4E9)) {
      newState.relateddocList4E9 = nextProps.relateddocList4E9;
    }
    if (!isEqual(nextProps.relatedprjList4E9, this.props.relatedprjList4E9)) {
      newState.relatedprjList4E9 = nextProps.relatedprjList4E9;
    }
    if (!isEqual(nextProps.relatedwfList4E9, this.props.relatedwfList4E9)) {
      newState.relatedwfList4E9 = nextProps.relatedwfList4E9;
    }
    if (!isEqual(nextProps.relatemutilprjs4E9, this.props.relatemutilprjs4E9)) {
      newState.relatemutilprjs4E9 = nextProps.relatemutilprjs4E9;
    }
    this.setState(newState);
  }
  componentUnMount() {
    this.setState({ anonymous: 0 });
  }

  getInstance = (ref) => {
    if (!this.rich) {
      this.rich = ref;
    }
  };

  handleStatusChange = (status) => {
    if (status === 'ready') {
      this.richInstanceReady = true; // 也可以放在 state 之类的标识里，如果放在 store 等外部数据在组件卸载的时候要给成 false
    }
  };
  render() {
    let { richValue, anonymous, disableSubmit } = this.state;
    let {
      hasSubmit,
      noBottomInfo,
      isApproval,
      isCoworkTypeApprove,
      isCanAnonymous,
      coworkMainStore,
      coworkStoreMap,
      editType,
      accessoryPath,
      id,
      replyName,
      startupFocus = true,
    } = this.props;
    let bottomBarConfig = [];
    if (!noBottomInfo) {
      let { config = {} } = coworkMainStore;
      let { appStatus = {} } = config;
      // 此处是因为抛出去的新建dialog初始化的时候，没有初始化这个数据，原本是在进入协作主页的时候初始化的，所以此处得在匹配一下新建dialog的情况再次初始化一下
      if (appStatus.doc === undefined) {
        appStatus = coworkStoreMap.getMapStore(3).config.appStatus;
        if (JSON.stringify(appStatus) == '{}') {
          appStatus = coworkStoreMap.getMapStore(2).config.appStatus;
        }
        if (JSON.stringify(appStatus) == '{}') {
          appStatus = coworkStoreMap.getMapStore(1).config.appStatus;
        }
      }

      //-----------------------
      if (appStatus.doc == 1) {
        bottomBarConfig.push(
          this.createBrowserConfig(
            37,
            getLabel(126529, '文档'),
            'icon-coms-content-o',
            'relateddocList4E9',
            false,
          ),
        );
      }
      if (appStatus.workflow == 1) {
        bottomBarConfig.push(
          this.createBrowserConfig(
            152,
            getLabel(131692, '流程'),
            'icon-coms-Workflow-o',
            'relatedwfList4E9',
            false,
          ),
        );
      }
      if (appStatus.crm == 1) {
        bottomBarConfig.push(
          this.createBrowserConfig(
            18,
            getLabel(84236, '客户'),
            'icon-coms-currency-Customer',
            'relatedcusList4E9',
            false,
          ),
        );
      }
      if (appStatus.project == 1) {
        bottomBarConfig.push(
          this.createBrowserConfig(
            135,
            getLabel(22245, '项目'),
            'icon-coms-project',
            'relatemutilprjs4E9',
            false,
          ),
        );
      }
      if (appStatus.task == 1) {
        bottomBarConfig.push(
          this.createBrowserConfig(
            'prjtsk',
            getLabel(1332, '任务'),
            'icon-coms-currency-Task',
            'relatedprjList4E9',
            false,
          ),
        );
      }
      if (appStatus.attachment == 1) {
        if (!accessoryPath) {
          accessoryPath = toJS(coworkMainStore.content.accessoryPath) || {};
        }
        let datas = this.state.relatedaccList4E9 || [];
        datas = datas.map(data => ({
          fileExtendName: data.docextendname,
          fileid: data.id,
          filelink: data.url,
          filename: data.name,
          filesize: data.downName,
          // imgSrc	string	是	附件图标
          loadlink: data.downUrl,
          // showLoad	bool	否	是否可下载
          // showDelete	bool	否	是否可删除
          // isImg	bool	否	非图片模式下是表示文件是否是图片格式
          ...data,
        }));

        let uploadInfo = {};
        uploadInfo = {
          name: 'Upload', // 上传组件
          type: 'list', // 上传组件类型
          show: (
            <div className="wea-cowork-rich-button wea-cowork-upload-button">
              <i
                className="icon-coms-currency-Enclosure"
                title={getLabel(128095, ' 上传附件')}
              />
              {datas.length > 0 && <div className="red-point" />}
              <span
                className="button-text"
                title={
                  getLabel(385751, '附件上传(最大') +
                  accessoryPath.maxsize +
                  getLabel(83528, 'M/个)')
                }
              >
                {getLabel(132024, ' 附件')}
              </span>
            </div>
          ), // 使用 antd 图标
          uploadUrl: `/api/cowork/base/uploadOperate?secId=${accessoryPath.secId}`, // 上传地址
          category: accessoryPath.categorypath
            ? accessoryPath.categorypath
            : '-1', // 文档目录
          onListChange: (ids, list) => {
            this.setState({
              relatedaccList4E9: list,
            });
          },
          datas,
        };
        if (accessoryPath.maxsize && accessoryPath.maxsize !== '') {
          uploadInfo = { ...uploadInfo, maxUploadSize: accessoryPath.maxsize };
        }

        bottomBarConfig.push(uploadInfo);
      }
    }
    let rightList = [];
    if (hasSubmit) {
      if (isCanAnonymous == 1) {
        // rightList.push(<span ref='anonymous' style={{position:'relative', top: '4px' }}><WeaCheckbox onChange={this.changeAnonymous} value={anonymous} content={getLabel(18611, ' 匿名')}/>{/* <span className="ml5">{getLabel(18611, ' 匿名')}</span> */}</span>);
        rightList.push(
          <span
            ref="anonymous"
            style={
              bottomBarConfig.length > 0
                ? { position: 'relative', top: '4px' }
                : {}
            }
          >
            <WeaCheckbox
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaCheckbox@c3xrq8@anonymous`}
              onChange={this.changeAnonymous}
              value={anonymous}
              content={getLabel(18611, ' 匿名')}
            />
          </span>,
        );
        // width += 43;
      }
      rightList.push(
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@3zi604@submit`}
          className="wea-button-release"
          disabled={disableSubmit}
          onClick={this.submit}
          style={bottomBarConfig.length > 0 ? { top: '2px' } : {}}
        >
          <span>
            <span className="icon-coms-Release" />
            <span>
              {isCoworkTypeApprove == 1
                ? getLabel(15143, ' 提交审批')
                : editType == 'quote'
                ? getLabel(128123, ' 回复')
                : editType == 'comment'
                ? getLabel(675, ' 评论')
                : getLabel(615, ' 提交')}
            </span>
          </span>
        </Button>,
      );
      if (isApproval == 1) {
        // width += 100;
      } else {
        // width += 76;
      }
      rightList.push(
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@e3wbxp@cancel`}
          onClick={this.cancel}
          style={
            bottomBarConfig.length > 0
              ? { marginLeft: '10px', top: '2px' }
              : { marginLeft: '10px' }
          }
        >
          <span ref="cancel">{getLabel(201, '取消')}</span>
        </Button>,
      );
      // width += 76;
    }

    // @功能
    const {
      content: { cowork },
    } = coworkMainStore;
    let itemsVO;
    // let parterList;
    if (cowork) {
      itemsVO = cowork.itemsVO;
      // parterList = cowork.parterList;
    }
    const extentsConfig = [
      {
        name: 'At',
        // data:toJS(cowork&&parterList),
        request: {
          url: '/api/cowork/view/atList',
          type: 'GET',
          params: {
            coworkId: `${(cowork && itemsVO && itemsVO.id) || ''}`,
          },
        },
        pushMessageParams: {
          title: getLabel('18822', '协作提醒'),
          context: `${getLabel('518971', '您的协作:')}【${
            cowork && itemsVO && itemsVO.name
          }】${getLabel('518972', '有新交流')}`,
          groupCode: '17855',
          linkurl: `/spa/cowork/static/index.html#/cowork/${
            cowork && itemsVO && itemsVO.id
          }`,
          linkMobileUrl: `/spa/cowork/static4mobile/index.html#/detail?id=${
            cowork && itemsVO && itemsVO.id
          }`,
        },
        tipTitle: getLabel('507106', '在发表框中输入@可直接选择协作参与人'),
      },
    ];

    let placeholder = '';
    switch (editType) {
      case 'quote':
        placeholder = getLabel('516916', '引用发表');
        break;
      case 'comment':
        if (replyName) placeholder = `${getLabel(128123, '回复')} ${replyName}`;
        else placeholder = `${getLabel('82562', '评论内容')}...`;
        break;
      default:
        placeholder = '';
    }

    return (
      <WeaRichText
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaRichText@gl6tqn`}
        id={id || ''}
        ls={true}
        value={richValue}
        ckConfig={{
          toolbar: [
            { name: 'document', items: ['Source'] },
            {
              name: 'paragraph',
              items: [
                'JustifyLeft',
                'JustifyCenter',
                'JustifyRight',
                '-',
                'NumberedList',
                'BulletedList',
              ],
            },
            { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
            { name: 'colors', items: ['TextColor'] },
            {
              name: 'basicstyles',
              items: ['Bold', 'Italic', 'Underline', 'Strike'],
            },
            { name: 'insert', items: ['Image', 'Table', 'Smiley'] },
            { name: 'tools', items: ['Maximize'] },
          ],
          extraPlugins: 'autogrow',
          height: 150,
          autoGrow_minHeight: 150,
          // autoGrow_maxHeight: 600,
          removePlugins: 'resize',
          uploadUrl: '/api/blog/fileupload/uploadimage',
          placeholder,
          startupFocus,
        }}
        ref={this.getInstance}
        extentsConfig={editType ? extentsConfig : []} // editType用来区分新建和编辑协作的时候无@
        className="wea-cowork-rich-text"
        bottomBarConfig={bottomBarConfig}
        bootomBarStyle={
          bottomBarConfig.length === 0 ? { overflow: 'hidden' } : {}
        }
        bottomBarRight={rightList.length > 0 && { Component: rightList }}
        // onChange={v=> this.setState({richValue: v})}
        onStatusChange={this.handleStatusChange}
        onToolsChange={this.onToolsChange}
      />
    );
  }

  getValue = () => {
    let value = this.state.richValue;
    if (this.richInstanceReady) {
      value = this.rich.getData();
    }
    return value;
  };

  getRichData = () => {
    let value = '';
    if (this.richInstanceReady) {
      value = this.rich.getData();
    }
    return value;
  };

  setValue = (v) => {
    if (this.richInstanceReady) {
      value = this.rich.setData(v);
    }
    this.setState({
      richValue: v,
    });
  };

  getSubmitParams = () => {
    let {
      richValue,
      anonymous,
      atUserIds,
      relatedaccList4E9 = [],
      relatedcusList4E9 = [],
      relateddocList4E9 = [],
      relatedprjList4E9 = [],
      relatedwfList4E9 = [],
      relatemutilprjs4E9 = [],
    } = this.state;
    let remark = richValue;
    if (this.richInstanceReady) {
      remark = this.rich.getData();
    }
    let params = { remark, isAnonymous: anonymous, atUserIds };
    params.relatedprj = relatedprjList4E9.map(obj => obj.id).join();
    params.relatedcus = relatedcusList4E9.map(obj => obj.id).join();
    params.relatedwf = relatedwfList4E9.map(obj => obj.id).join();
    params.relateddoc = relateddocList4E9.map(obj => obj.id).join();
    params.projectIDs = relatemutilprjs4E9.map(obj => obj.id).join();
    params.relatedacc = relatedaccList4E9
      .map(obj => obj.fileid || obj.id)
      .join();
    return params;
  };
  submit = () => {
    if (this.props.approvalStatus == 1) {
      message.info(getLabel(83249, '主题处于待审批状态禁止发言'));
      return;
    }

    if (this.richInstanceReady) {
      if (this.rich.state && this.rich.state.maximize) {
        // 判断是否是在全屏模式下
        this.rich.onFullScreen();
      }

      this.rich.pushAtMessage(() => {});
    }

    if (isFunction(this.props.submit)) {
      if (!this.state.disableSubmit) {
        this.setState(
          {
            disableSubmit: true,
            atUserIds:
              this.richInstanceReady && this.rich.getChooseId().join(','),
          },
          () => {
            let result = this.props.submit(this.getSubmitParams(), () => {
              this.setState({
                disableSubmit: false,
              });
            });
            // 出错处理
            if (result === false) {
              this.setState({
                disableSubmit: false,
              });
            }
          },
        );
      }
    }
  };
  cancel = () => {
    if (isFunction(this.props.cancel)) {
      this.props.cancel(this.state.richValue);
    }
  };
  changeAnonymous = (value) => {
    this.setState({ anonymous: value });
  };
  clear = () => {
    this.setState({
      ...this.initValue,
    });
  };
  onToolsChange = (...arg) => {
    let list = arg[2] || [],
      type = arg[3] || '';
    if (type == 'image') {
      let str = list.reduce(
        (sum, img) =>
          // return sum + `<img src="${img.imgSrc}"/>&#8203;`
          `${sum}&nbsp;<img src="${img.imgSrc}"/>&nbsp;`,
        '',
      );
      return str;
    }
    let key = '';
    switch (type) {
      case 37:
        key = 'relateddocList4E9';
        break;
      case 152:
        key = 'relatedwfList4E9';
        break;
      case 18:
        key = 'relatedcusList4E9';
        break;
      case 135:
        key = 'relatemutilprjs4E9';
        break;
      case 'prjtsk':
        key = 'relatedprjList4E9';
        break;
      default:
        break;
    }
    let newState = {};
    newState[key] = list;
    this.setState(newState);
    return ' ';
  };
  createBrowserConfig = (type, text, icon, key, isSingle, att) => {
    let replaceDatas = this.state[key] || [];
    return {
      name: att || 'Browser',
      show: (
        <div className="wea-cowork-rich-button">
          <i className={icon} />
          {replaceDatas.length > 0 && <div className="red-point" />}
          <span className="button-text">{text}</span>
        </div>
      ),
      title: text,
      memorise: true,
      type,
      isSingle,
      replaceDatas,
    };
  };
  focus = () => {
    if (this.richInstanceReady) {
      this.rich && this.rich.focus('last');
    }
  };
}

export default CoworkRichText;
